package com.top.mall.main.mine

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.view.View
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.BarUtils
import com.module.lemlin.http.Status
import com.module.lemlin.http.msg
import com.module.lemlin.owner.OwnerViewModeActivity
import com.top.mall.R
import com.top.mall.app.BaseApplication
import com.top.mall.entity.CartList
import com.top.mall.entity.CartType
import com.top.mall.entity.GoodsCollect
import com.top.mall.jetpack.vm.CartViewModel
import com.top.mall.main.cart.CartActivity
import com.top.mall.main.goods.adapter.GoodsCollectAdapter
import kotlinx.android.synthetic.main.activity_mine_collection.*
import kotlinx.android.synthetic.main.include_goods_bottom.*
import java.lang.StringBuilder
import java.text.DecimalFormat

class MineCollectionActivity : OwnerViewModeActivity<CartViewModel>() {

    companion object {
        fun open(activity: Activity) {
            val intent = Intent(activity, MineCollectionActivity::class.java)
            activity.startActivity(intent)
        }
    }

    private val mGoodsCollectAdapter: GoodsCollectAdapter =
        GoodsCollectAdapter()

    override fun viewModel(): CartViewModel {
        return createViewModel()
    }

    override val layoutResId: Int
        get() = R.layout.activity_mine_collection

    override fun stateBar(): StatusBar {
        return StatusBar(view = flMineCollectionBar)
    }

    override fun initView() {

        imageViewBack.setOnClickListener { finish() }
        BarUtils.setStatusBarColor(this, Color.WHITE)

        rvCollectionGoods.apply {
//            val decoration = SpacingItemDecoration(
//                vGap = ConvertUtils.dp2px(10f),
//                hGap = ConvertUtils.dp2px(13f)
//            )
//            addItemDecoration(decoration)
            itemAnimator?.changeDuration = 0
        }.adapter = mGoodsCollectAdapter

        mGoodsCollectAdapter.setOnItemChildClickListener { adapter, view, position ->
            val itemData: GoodsCollect = mGoodsCollectAdapter.getItem(position)
            when (view.id) {
                R.id.flCategoryBodyPlus -> {
                    val num: Int = itemData.cart.goods_num + 1
                    if (itemData.cart.id == 0 || itemData.cart.goods_num == 0) {
                        viewModel.cartAdd(itemData.id, num, position)
                    } else {
                        viewModel.cartChangeNum(itemData.cart.id, num, position, true)
                    }
                }
                R.id.flCategoryBodyReduce -> {
                    val num: Int = itemData.cart.goods_num - 1
                    if (num == 0) {
                        viewModel.cartDelete(arrayOf(itemData.cart.id), CartType.DELETE, position)
                    } else {
                        viewModel.cartChangeNum(itemData.cart.id, num, position, true)
                    }
                }
            }
        }
        //去购物车
        tvGoodsBottomGoCart.setOnClickListener {
            CartActivity.open(activity = this)
        }
    }

    override fun initData() {

        viewModel.userCollect()
    }

    override fun initViewMode() {
        super.initViewMode()

        //监听物品列表数据
        viewModel.userCollectLiveData.observe(this as LifecycleOwner, Observer { response ->

            when (response.status) {
                Status.START -> {
                    mGoodsCollectAdapter.setEmptyView(createLoadingView())
                }
                Status.SUCCESS -> {
                    response.data?.data?.let {
                        if (it.size == 0) {
                            mGoodsCollectAdapter.setEmptyView(createNullDataView())
                        }
                        mGoodsCollectAdapter.setNewInstance(it)
                    }
                }
                Status.FAILURE -> {
                    mGoodsCollectAdapter.setEmptyView(createLoadingView())
                }
            }
        })

        //监听购物车添加
        viewModel.cartAddLiveData.observe(this as LifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            response.data?.let {
                mGoodsCollectAdapter.setData(it.position, it.goods_num, it.cart_id)
            }
        })

        //监听购物车加减
        viewModel.cartChangeNumLiveData.observe(this as LifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            response.data?.let {
                mGoodsCollectAdapter.setData(it.position, it.goods_num)
            }
        })

        //监听购物车删除
        viewModel.cartDeleteLiveData.observe(this as LifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            response.data?.let {
                mGoodsCollectAdapter.setData(it.position, 0)
            }
        })

        BaseApplication.getCartListLiveData().observe(this, Observer {
            fillDataUndulate(it)
        })
    }


    private fun fillDataUndulate(cartList: MutableList<CartList>) {

        tvGoodsBottomBadgeNum.text = cartList.size.toString()

        var num: Int = 0
        var price: Double = 0.00
        cartList.filter { it.isSelected }.forEach {
            num += it.goods_num
            price += it.goods_num * if (it.active_price == "0")
                it.goods_price.toDouble()
            else it.active_price.toDouble()
        }

        tvGoodsBottomSelectNum.text = StringBuilder()
            .append("已选(").append(num).append(")")
        tvGoodsBottomPrice.text = StringBuilder()
            .append("￥").append(DecimalFormat(("############0.00")).format(price))
    }

    private fun createLoadingView(): View {
        return layoutInflater.inflate(R.layout.dialog_load_style_2, null)
    }

    private fun createNullDataView(): View {
        return layoutInflater.inflate(R.layout.view_empty_null, null)
    }

}